<template>
    <div class="nav-wrapper flex-row justify-between align-center">
        <logo :collapse="true" />
        <div class="header_box flex-row">
            <div class="header_info">
                <span class="user_name">{{ accountInfo.userName }}，欢迎您</span>
            </div>
            <div class="horizotal_item">
                <template v-if="horizontal">
                    <horizonttal-side/>
                </template>
            </div>
            <div class="right-menu flex">
                <!-- <div class="audio_box">
                    <span class="label">报警音效</span>
                    <a-switch v-model="isAudio" @change="changeAudio" />
                </div> -->
                <!-- 消息通知 -->
                <!-- <div class="right-menu-item pointer boxHover" style="margin-right: 15px">
                    <a-popover placement="bottom" trigger="click">
                        <template slot="content">
                            <div style="text-align: center">
                                <a-button-group>
                                    <a-button :type="form.messageStatus == 0 ? 'primary' : ''" @click="switchType(0)"
                                        >待确认</a-button
                                    >
                                    <a-button :type="form.messageStatus == 1 ? 'primary' : ''" @click="switchType(1)"
                                        >已确认</a-button
                                    >
                                </a-button-group>
                            </div>
                            <div class="popover_body" ref="scrollview" @scroll="updateScroll">
                                <div
                                    class="message_item"
                                    v-for="(item, index) in messageList"
                                    :key="item.messageId"
                                    @click="confirmMessage(item, index)"
                                >
                                    <div class="message_side">
                                        <p class="desc">{{ item.messageContent }}</p>
                                        <p class="time">{{ item.createTime }}</p>
                                    </div>
                                    <a-button size="small" type="link" v-if="item.messageStatus == 0"
                                        >确认消息</a-button
                                    >
                                </div>
                                <a-empty class="empty" v-if="total == 0" description="暂无消息" />
                                <p class="end" v-if="messageList.length == total && total != 0">
                                    ～已经到底了～
                                </p>
                            </div>
                        </template>
                        <a-badge :count="count" :overflow-count="99" :offset="[3, -4]">
                            <svg-icon icon="bell" :size="18" />
                        </a-badge>
                    </a-popover>
                </div> -->
                <!-- 配置主题 -->
                <!-- <div class="right-menu-item pointer boxHover" @click="isShowSystem = true">
                    <svg-icon icon="system" :size="18" />
                </div>
                <nav-user class="right-menu-item pointer boxHover flex-sub" /> -->

                <!-- <div class="right-menu-item header_search">
                    <a-input-group compact class="flex-row">
                        <a-select default-value="首页">
                            <a-icon slot="suffixIcon" type="caret-down" />
                            <a-select-option value="首页">首页</a-select-option>
                            <a-select-option value="培训">培训</a-select-option>
                        </a-select>
                        <a-input class="search" placeholder="请输入关键词">
                            <a-icon slot="suffix" class="icon" type="search" @click="searchKeyword" />
                        </a-input>
                    </a-input-group>
                </div> -->
                <!-- 设置 -->
                <template v-if="layout!='vertical'">
                    <router-link class="right-menu-item setting_item pointer" to="/setting/config/index">
                        <a-icon type="setting" />
                    </router-link>
                    <router-link class="right-menu-item setting_item pointer" to="/setting/user/index">
                        <a-icon type="user" />
                    </router-link>
                </template>
                <!-- <div class="right-menu-item pointer">
                    <a-icon type="bell" class="header_icon" />
                </div> -->
                <!-- 全屏显示 -->
                <div class="right-menu-item pointer" @click.stop="screenFull">
                    <a-icon :type="isFullscreen ? 'fullscreen-exit' : 'fullscreen'" class="header_icon" />
                </div>
                <!-- 退出 -->
                <div class="right-menu-item pointer" @click="logout">
                    <a-icon type="poweroff" class="header_icon" />
                </div>
            </div>
        </div>

        <system-setting v-if="isShowSystem" @hide="isShowSystem = false" />
    </div>
</template>

<script>
import navUser from './navUser';
import screenfull from 'screenfull';
import breadCrumb from './breadCrumb';
import { mapState } from 'vuex';
import { getCache } from '@/utils/session';
import logo from '../sideBar/logo';
import { updateInfo, remoteList } from '@/api/message';
import SystemSetting from './systemSetting.vue';
import HorizonttalSide from '../sideBar/horizontalSide.vue'

export default {
    name: 'navBar',
    inject: ['playAudio', 'closeAudio', 'clearTip'],
    props: {
        collapsed: {
            type: Boolean,
            default: true
        },
        horizontal: {
            type: Boolean,
            default: false
        }
    },
    components: { navUser, breadCrumb, logo,HorizonttalSide, SystemSetting },
    computed: {
        isAudio: {
            get() {
                return this.$store.state.setting.isAudio;
            },
            set(e) {
                this.$store.dispatch('setting/changeOpenAudio', e);
            }
        },
        ...mapState({
            layout: state => state.setting.layout,
            accountInfo: state => state.user.accountInfo,
            routes: state => state.user.routes,
        })
    },
    data() {
        return {
            breadList: [
                {
                    path: '/',
                    meta: { title: '首页', icon: 'dashboard' }
                }
            ],
            count: 0,
            isFullscreen: false,
            total: -1,
            messageList: [],
            form: {
                messageStatus: 0,
                page: 1,
                size: 5
            },
            isShowSystem: false,
            permissionRoutes:[]
        };
    },
    created(){
        this.permissionRoutes = [];
        this.dealUserRoutes(this.routes);
    },
    mounted() {
        this.searchMessage(true);
        this.$nextTick(() => {
            const scrollview = this.$refs['scrollview'];
            // 尾部的 true 最好加上，我这边测试没加 true ，拖拽滚动条无法监听到滚动，加上则可以监听到拖拽滚动条滚动回调
            if (scrollview) {
                scrollview.addEventListener('scroll', this.updateScroll, true);
            }
        });
    },
    methods: {
        //处理用户可有的权限页面
        dealUserRoutes(routes){
            if(routes && routes.length){
                routes.map(item=>{
                    if(item.menuType=='C'){
                        this.permissionRoutes.push(item);
                    }
                    if(item.children){
                        this.dealUserRoutes(item.children)
                    }
                })
            }
        },
        //搜索
        searchKeyword() {
            console.log('搜索');
        },
        async confirmMessage(item, index) {
            if (item.messageStatus == 1) return false;
            try {
                item.messageStatus = 1;
                await updateInfo(item);
                // this.messageList.splice(index,1);
                // this.count -=1;
                // this.total = this.count;
                this.searchMessage();
            } finally {
                console.log('完成信息');
            }
        },
        //退出账号
        async logout() {
            this.$confirm({
                title: '操作提示',
                content: '确认退出当前管理账号？',
                onOk: async () => {
                    try {
                        await this.$store.dispatch('setting/changeSpin', true);
                        await this.$store.dispatch('user/logout');
                        await this.$store.dispatch('setting/changeSpin', false);
                        this.$message.success('退出成功');
                        this.clearTip();
                        await this.$store.dispatch('tagsView/clearTag');
                        let tenant = getCache('tenant') || 'master';
                        this.$router.replace({
                            path: `/${tenant}/login`
                        });
                    } catch (err) {
                        await this.$store.dispatch('setting/changeSpin', false);
                    }
                },
                onCancel() {}
            });
        },
        toggleOpen() {
            this.$store.commit('setting/TOGGLE_OPEN');
        },
        toggleMenu() {
            this.$store.commit('setting/TOGGLE_BAR');
        },
        screenFull() {
            if (!screenfull.isEnabled) {
                this.$message.warning('不好意思，你的电脑不支持全屏，赶紧换个电脑吧，谢谢~');
                return false;
            }
            screenfull.toggle();
            this.isFullscreen = !this.isFullscreen;
        },
        changeVisible() {
            this.$store.dispatch('setting/changeVisible', true);
        },
        switchType(status) {
            this.form.messageStatus = status;
            this.messageList = [];
            this.form.page = 1;
            this.total = -1;
            this.searchMessage();
        },
        updateScroll(event) {
            let el = event.target;
            if (el.scrollTop + el.clientHeight + 1 >= el.scrollHeight) {
                if (this.messageList.length < this.total) {
                    this.form.page += 1;
                    this.searchMessage();
                }
                console.log('到底啦');
            }
        },
        async searchMessage(isTip = false) {
            try {
                let res = await remoteList(this.form);
                let { list, total } = res.data;
                if (this.form.messageStatus == 0) {
                    this.count = total;
                    if (isTip && total) {
                        let item = list[0];
                        this.$notification.warning({
                            message: '消息提醒',
                            description: item.messageContent,
                            duration: 0,
                            style: { wordWrap: 'break-word', whiteSpace: 'pre-wrap' },
                            btn: h => {
                                return h(
                                    'a-button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        on: {
                                            click: async () => {
                                                item.messageStatus = 1;
                                                await updateInfo(item);
                                                this.messageList.splice(0, 1);
                                                this.count--;
                                                this.searchMessage();
                                                this.$notification.close(item.messageId);
                                            }
                                        }
                                    },
                                    '已知晓'
                                );
                            },
                            key: item.messageId
                        });
                    }
                }
                this.total = total;
                this.messageList = [...this.messageList, ...list];
            } finally {
                console.log('信息获取成功');
            }
        },
        changeAudio(e) {
            this.$store.dispatch('setting/changeOpenAudio', e);
            this.playAudio('', 'realtime', false);
            if (!e) {
                this.closeAudio();
            }
        }
    },
    beforeDestroy() {
        // 获取指定元素
        const scrollview = this.$refs['scrollview'];
        // 移除监听
        if (scrollview) {
            scrollview.removeEventListener('scroll', this.updateScroll, true);
        }
    }
};
</script>
<style lang="scss" scoped>
.empty {
    margin-top: 20px;
}
.setting_item {
    flex: 1;
    text-align: center;
    font-size: 20px;
    color: #fff!important;
}
.end {
    margin-top: 10px;
    font-size: 12px;
    color: #999;
    text-align: center;
}
.header_search {
    padding: 0 5px !important;
    background: rgba($color: #fff, $alpha: 0.2);
    border-radius: 20px;
    .ant-input-group {
        ::v-deep .ant-select {
            &::after {
                content: '';
                position: absolute;
                right: 0;
                top: 7px;
                bottom: 7px;
                width: 1px;
                background: rgba($color: #fff, $alpha: 0.5);
                z-index: 9;
            }
            .ant-select-selection {
                color: #fff;
                background-color: unset !important;
                border: none;
                box-shadow: none;
                .anticon {
                    color: #fff;
                }
            }
        }
        ::v-deep .ant-input {
            color: #fff;
            background: unset;
            border: none;
            &:focus {
                /* 去除获取焦点时的样式 */
                border: none;
                box-shadow: none;
            }
        }
        .icon {
            color: #fff;
        }
    }
}

.popover_body {
    width: 280px;
    height: 200px;
    margin: 0 -15px 0 -10px;
    overflow-y: auto;

    .message_item {
        display: flex;
        padding: 10px;
        // align-items: center;
        border-bottom: 1px solid #e4e4e4;

        &:last-child {
            border-bottom: none;
        }
        .message_side {
            flex: 1;
        }
        .desc {
            font-size: 13px;
            color: #666;
        }

        .time {
            font-size: 12px;
            color: #aaa;
        }
    }
}

.audio_box {
    margin-right: 5px;
    display: flex;
    align-items: center;

    .label {
        margin-right: 5px;
    }
}

.nav-wrapper {
    height: 54px;
    overflow: hidden;
    position: relative;
    -webkit-box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

    .boxHover {
        &:hover {
            background: rgba(0, 0, 0, 0.025);
        }
    }
    .header_info{
        flex-shrink: 0;
    }
    .nav-fold {
        padding: 0 18px;
        height: 100%;
        cursor: pointer;
        font-size: 20px;
        line-height: 58px;
        transition: all 0.3s, padding 0s;
    }
    .horizotal_item{
        flex: 1;
        margin: 0 20px;
        width: calc(100vw - 174px - 600px);
    }
    .right-menu {
        flex-shrink: 0;
        height: 54px;
        margin-right: 20px;
        align-items: center;
        // width: 280px;
        .right-menu-item {
            padding: 0 15px;
            &:hover {
                opacity: 0.7;
            }
        }
    }
}
</style>
